import { reqLogin, reqUserInfo, reqGetUserInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }

}
const actions = {
  async login(context, data) {
    const res = await reqLogin(data)
    console.log(res)
    const token = res.data
    context.commit('setToken', token)
  },
  // 获取用户资料的action
  async setUserInfo(context) {
    const { data: data1 } = await reqUserInfo()
    // console.log(res, 666)
    const { data: data2 } = await reqGetUserInfo(data1.userId)

    const resultObj = {
      ...data1,
      ...data2
    }
    // console.log(resultObj)
    context.commit('setUserInfo', resultObj)
    return resultObj
  },
  logout(context) {
    // 删除token
    context.commit('removeToken')
    // 删除用户资料
    context.commit('removeUserInfo')
  }
}
// setUserInfo(context) => {
//   return new Promise((resolve,reject) => {
//     reqUserInfo(data).then((res)=>{
//       const res=res.data.data
//     })
//   })
// }
// return new Promise((resolve, reject) = {
//       reqLogin(data).then(res=> {
// const newToken=res.data.data
// context.commit('setToken',newToken)
// resolve(res)
//       }).catch(error=>{
//         reject(error)
//       })
//     })
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
